package com.ikingtech.platform.service.office.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.office.model.dto.AffixFileDto;
import com.ikingtech.framework.sdk.office.model.vo.AffixFileVo;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.office.entity.AffixFile;
import com.ikingtech.platform.service.office.mapper.AffixFileMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
public class AffixFileService extends ServiceImpl<AffixFileMapper, AffixFile> {


    /**
     * 保存
     *
     * @param dto dto
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> add(AffixFileDto dto) {
        if (StringUtils.isBlank(dto.getBusinessId())) {
            throw new FrameworkException("业务id不能为空");
        }
        AffixFile file = dto.copy(new AffixFile());
        file.setId(Tools.Id.uuid());
        file.insert();
        return R.ok(file.getId());
    }

    /**
     * 删除
     *
     * @param id id
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> delete(String id) {
        AffixFile file = this.getById(id);
        if (ObjectUtils.isEmpty(file)) {
            return R.failed("附件不存在");
        }
        file.deleteById();
        return R.ok(id);
    }

    /**
     * 由业务id查询
     *
     * @param businessId 业务标识
     * @return 执行结果
     */
    public R<List<AffixFileVo>> queryByBusinessId(String businessId) {
        List<AffixFile> list = this.list(new QueryWrapper<AffixFile>().lambda().eq(AffixFile::getBusinessId, businessId));
        if (ObjectUtils.isEmpty(list)) {
            return R.ok(new ArrayList<>());
        }
        return R.ok(list.stream().map(f -> f.copy(new AffixFileVo())).collect(Collectors.toList()));
    }

    /**
     * 添加批
     *
     * @param affixFiles 签署文件
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> addBatch(List<AffixFileDto> affixFiles) {
        long count = affixFiles.stream().filter(a -> StringUtils.isBlank(a.getBusinessId())).count();
        if (count > 0) {
            throw new FrameworkException("业务id不能为空");
        }
        this.saveBatch(affixFiles.stream().map(f -> {
            AffixFile file = f.copy(new AffixFile());
            if (StringUtils.isBlank(f.getOssFileId())) {
                file.setOssFileId(f.getId());
            }
            file.setId(Tools.Id.uuid());
            return file;
        }).collect(Collectors.toList()));
        return R.ok();
    }

    /**
     * 删除批处理
     *
     * @param ids id
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> deleteBatch(List<String> ids) {
        List<AffixFile> list = this.baseMapper.selectBatchIds(ids);
        if (ids.size() != list.size()) {
            return R.failed("附件信息不存在");
        }
        this.removeBatchByIds(ids);
        return R.ok();
    }

    /**
     * 由业务id删除
     *
     * @param businessId 业务标识
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> deleteByBusinessId(String businessId) {
        this.remove(new QueryWrapper<AffixFile>().lambda()
                .eq(AffixFile::getBusinessId, businessId)
        );
        return R.ok();
    }

    /**
     * 根据业务id集合查询map
     *
     * @param businessIds 业务id集合
     * @return map
     */
    public Map<String, List<AffixFileVo>> mapByBusinessIds(List<String> businessIds) {
        if (CollUtil.isEmpty(businessIds)) {
            return new HashMap<>();
        }
        List<AffixFile> list = this.list(Wrappers.<AffixFile>lambdaQuery().in(AffixFile::getBusinessId, businessIds));
        if (list.isEmpty()) {
            return new HashMap<>();
        }
        List<AffixFileVo> taskExecuteRes = Tools.Coll.convertList(list, e -> {
            AffixFileVo affixFileVo = new AffixFileVo();
            BeanUtils.copyProperties(e, affixFileVo);
            return affixFileVo;
        });
        return taskExecuteRes.stream().collect(Collectors.groupingBy(AffixFileVo::getBusinessId));
    }
}
